package com.shamar.blog.web.frontend;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shamar.blog.dto.BlogCategoryExecution;
import com.shamar.blog.dto.BlogContentExecution;
import com.shamar.blog.entity.BlogCategory;
import com.shamar.blog.entity.BlogContent;
import com.shamar.blog.entity.BlogUser;
import com.shamar.blog.enums.BlogContentStateEnum;
import com.shamar.blog.service.BlogCategoryService;
import com.shamar.blog.service.BlogContentService;
import com.shamar.blog.util.HttpServletRequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@Controller
@RequestMapping("/community")
/**
 * @author shamarfang
 * @date 2020-08-01 17:00
 * @desc 博客相关 控制器
 */
public class BlogController {
    Logger logger = LoggerFactory.getLogger(BlogController.class);

    @Autowired
    private BlogContentService blogContentService;
    @Autowired
    private BlogCategoryService blogCategoryService;

    @GetMapping(value = "view_blog")
    @ResponseBody
    public ModelAndView viewBlog(HttpServletRequest request){
        logger.info("============博文浏览开始============");
        //定义返回值
        ModelAndView  model  =  new ModelAndView("frontend/blog_content");
        //判断登录用户
        BlogUser blogUser = (BlogUser) request.getSession().getAttribute("currentBlogUser");
        if (Objects.nonNull(blogUser)){
            model.addObject("user",blogUser);
        }
		//获取博文id
        int contentId = HttpServletRequestUtil.getInt(request, "i");
        BlogContent blogContent = blogContentService.selectByPrimaryKey(contentId).getBlogContent();
        if (blogContent!=null){
            model.addObject("blogContent",blogContent);
        }
        logger.info("============博文浏览结束============");
        return model;
    }
    /**
     * 获取最近博文数据
     * @param request
     * @return
     */
    @GetMapping(value = "/push_blog")
    public ModelAndView pushBlog(HttpServletRequest request) {
        //定义返回页面
        ModelAndView  model  =  new ModelAndView("frontend/blogedit");
        //		获取所有的分类
        BlogCategoryExecution blogCategoryExecution = blogCategoryService.getAllCategory();
        List<BlogCategory> allCategory = blogCategoryExecution.getBlogCategoryList();
        model.addObject("allCategory",allCategory);
        return model;
    }


    @PostMapping(value = "/save_blog")
    @ResponseBody
//    @RequestMapping(value = "save_blog",method = {RequestMethod.GET,RequestMethod.POST})
    public Map<String,Object> saveBlog(HttpServletRequest request){
        BlogUser blogUser = (BlogUser) request.getSession().getAttribute("currentBlogUser");
        //定义返回值
        Map<String,Object> modelMap = new HashMap<>();
        //检查是否登录
        if (blogUser == null){
            modelMap.put("success", false);
            modelMap.put("errMsg", "发布博客前必须登录");
            return modelMap;
        }
        //定义空博客对象
        BlogContent blogContent = new BlogContent();
        ObjectMapper mapper = new ObjectMapper();
        String blogContentStr = HttpServletRequestUtil.getString(request, "BlogContentStr");
        //1.以上接收前端传递过来的信息,下面使用jackson json databind转换为博客实体类
        try {
            //获取前端传来的数据
            blogContent = mapper.readValue(blogContentStr, BlogContent.class);
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.toString());
            return modelMap;
        }
        //2. 新增分类
        if (Objects.nonNull(blogContent)) {
            BlogContentExecution blogContentExecution = null;
            try {
                //设置发布用户id
                blogContent.setUserId(blogUser.getId());
                //调用Service层
                if (Objects.isNull(blogContent.getId())) {
                    blogContentExecution = blogContentService.addBlogContent(blogContent,1);
                }else {
                    blogContentExecution = blogContentService.updateBlogContent(blogContent);
                }
                if (blogContentExecution.getState() == BlogContentStateEnum.SUCCESS.getState()) {
                    modelMap.put("success", true);
                //若shop创建成功，则加入session中，作为权限使用
                } else {
                    modelMap.put("success", false);
                    modelMap.put("errMsg", blogContentExecution.getStateInfo());
                }
            } catch (Exception e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.toString());
                return modelMap;
            }
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "请不要发布空信息");
        }
        return modelMap;
    }

    @GetMapping(value = "/edit_blog")
    public ModelAndView editBlog(HttpServletRequest request, @RequestParam("id") Integer id, Model model){
        BlogUser blogUser = (BlogUser) request.getSession().getAttribute("currentBlogUser");
        if(Objects.isNull(blogUser)) {
            //没有登录情况下不能进行博客编辑
            model.addAttribute("nologin","nologin");
            return new ModelAndView("frontend/blogupdate","blogModel",model);
        }
        BlogContent blogContent = blogContentService.selectByPrimaryKey(id).getBlogContent();
        if (!blogUser.getId().equals(blogContent.getUserId())){
            //非发布者不能进行编辑
            model.addAttribute("noPermission","noPermission");
            return new ModelAndView("frontend/blogupdate","blogModel",model);
        }
        model.addAttribute("blog",blogContent);
        //获取所有的分类
        BlogCategoryExecution blogCategoryExecution = blogCategoryService.getAllCategory();
        List<BlogCategory> allCategory = blogCategoryExecution.getBlogCategoryList();
        model.addAttribute("allCategory",allCategory);
        return new ModelAndView("frontend/blogupdate","blogModel",model);
    }

    @DeleteMapping(value = "/delete_blog/{id}")
    @ResponseBody
    public Map<String,Object> deleteBlog(HttpServletRequest request, @PathVariable("id") Integer id){
        //定义返回值
        Map<String,Object> modelMap = new HashMap<>();
        BlogUser blogUser = (BlogUser) request.getSession().getAttribute("currentBlogUser");
        if (Objects.isNull(blogUser)) {
            //没有登录情况下不能删除
            modelMap.put("success",false);
            modelMap.put("errMsg","请先登录再操作");
            return modelMap;
        }
        BlogContent blogContent = blogContentService.selectByPrimaryKey(id).getBlogContent();
        if(!blogUser.getId().equals(blogContent.getUserId())){
            //没有登录情况下不能删除
            modelMap.put("success",false);
            modelMap.put("errMsg","非发布者不能进行删除操作!");
            return modelMap;
        }
        BlogContentExecution blogContentExecution = blogContentService.deleteByPrimaryKey(id);
        if (blogContentExecution.getStateInfo().equals(BlogContentStateEnum.SUCCESS.getStateInfo())){
            modelMap.put("success",true);
        }
        else {
            modelMap.put("success",false);
            modelMap.put("errMsg","网络出错,请稍后重试");
        }
        return modelMap;
    }

}
